#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ollama,json,sys,readline,re,random,string,uuid,datetime
# Import the database connector functions
from db_connector import create_test_case, update_test_case, test_connection

# Check if database connection is available
DB_AVAILABLE = test_connection()
if DB_AVAILABLE:
    print("MySQL database connection is available. Test cases will be saved to database.")
else:
    print("MySQL database connection is not available. Test cases will be saved to file only.")

def validated_input(prompt, validation_func, error_msg):
    """通用验证输入函数"""
    while True:
        try:
            value = input(prompt).strip()
            if validation_func(value):
                return value
            print(error_msg)
        except KeyboardInterrupt:
            print("\n用户中断输入")
            sys.exit(0)
            
def interactive_input():
    """交互式输入字段值"""
    print("\n===== 测试用例生成器 =====")
    print("请输入以下信息（按 Ctrl+C 退出）:")

    try:
        name = validated_input(
            "场景名称: ",
            lambda x: x != "",
            "错误: 名称不能为空!"
        )
        
        # 添加场景描述输入
        description = validated_input(
            "场景描述 (详细描述该功能的用途和业务场景): ",
            lambda x: True,  # 任何输入都有效，但鼓励详细描述
            ""
        )
        
        # 如果描述为空，使用场景名称作为默认描述
        if not description:
            description = name
            print(f"使用场景名称作为描述: {description}")

        number = validated_input(
            "用例数量: ",
            lambda x: x.isdigit() and int(x) > 0,
            "错误: 必须输入正整数!"
        )
        
        # 添加优先级策略选择
        print("\n优先级策略:")
        print("1) 基于重要性")
        print("2) 全部高优先级(P0)")
        print("3) 全部中优先级(P1)")
        print("4) 全部低优先级(P2)")
        
        priority_strategy = validated_input(
            "选择优先级策略 (1-4，默认1): ",
            lambda x: x in ["", "1", "2", "3", "4"],
            "错误: 请输入1-4之间的数字!"
        )
        
        if priority_strategy == "":
            priority_strategy = "1"
        
        # 添加测试用例类型选择
        print("\n测试用例类型:")
        print("1) 功能测试")
        print("2) 性能测试")
        print("3) 自动化测试")
        
        test_type = validated_input(
            "选择测试用例类型 (1-3): ",
            lambda x: x in ["1", "2", "3"],
            "错误: 请输入1-3之间的数字!"
        )
        
        # 将选择转换为类型名称
        type_map = {
            "1": "功能测试",
            "2": "性能测试",
            "3": "自动化测试"
        }
        
        # 添加是否生成测试数据选择
        generate_test_data = validated_input(
            "\n生成测试数据 (y/n，默认y): ",
            lambda x: x.lower() in ["", "y", "n", "yes", "no"],
            "错误: 请输入y或n!"
        )
        
        generate_test_data = generate_test_data.lower() in ["", "y", "yes"]
        
        # 添加ID前缀选择
        id_prefix = validated_input(
            "ID前缀 (留空使用默认值F/P/A): ",
            lambda x: True,  # 任何输入都有效
            ""
        )
        
        # 如果未提供前缀，则根据类型设置默认前缀
        if not id_prefix:
            prefix_map = {
                "1": "F",  # 功能测试
                "2": "P",  # 性能测试
                "3": "A"   # 自动化测试
            }
            id_prefix = prefix_map[test_type]
            print(f"使用默认前缀: {id_prefix}")

        return {
            "name": name,
            "description": description,  # 使用用户输入的描述
            "number": int(number),
            "test_type": type_map[test_type],
            "id_prefix": id_prefix,
            "priority_strategy": priority_strategy,
            "generate_test_data": generate_test_data
        }

    except KeyboardInterrupt:
        print("\n用户中断输入")
        sys.exit(0)
        
def clean_json_response(text):
    """清理和修复常见的JSON格式问题"""
    # 移除可能的前缀说明文字（在第一个[之前的内容）
    start_idx = text.find('[')
    if start_idx > 0:
        text = text[start_idx:]
    
    # 移除可能的后缀说明文字（在最后一个]之后的内容）
    end_idx = text.rfind(']')
    if end_idx > 0 and end_idx < len(text) - 1:
        text = text[:end_idx+1]
    
    # 修复常见的JSON格式错误
    # 1. 单引号替换为双引号（但避免替换已经转义的单引号）
    text = re.sub(r"(?<!\\)'", '"', text)
    
    # 2. 确保属性名有双引号
    text = re.sub(r'([{,])\s*([a-zA-Z0-9_]+)\s*:', r'\1"\2":', text)
    
    # 3. 修复可能的尾随逗号
    text = re.sub(r',\s*([}\]])', r'\1', text)
    
    # 4. 处理JavaScript函数调用，如.repeat()
    text = re.sub(r'\.repeat\(\d+\)', lambda m: '"' + 'a' * 20 + '"', text)  # 替换.repeat(n)为实际重复的字符串
    
    # 5. 处理其他可能的JavaScript函数
    text = re.sub(r'\.[a-zA-Z]+\([^)]*\)', '""', text)  # 将其他JS函数调用替换为空字符串
    
    return text

def generate_case_id(prefix, index=None):
    """生成不重复的测试用例ID"""
    # 使用更精确的时间戳和随机字符生成绝对唯一的ID
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    # 添加毫秒以增加唯一性
    microseconds = datetime.datetime.now().microsecond // 1000
    
    if index is not None:
        # 使用索引和随机数生成ID
        random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=2))
        return f"{prefix}_{timestamp}_{microseconds:03d}_{index:03d}_{random_chars}"
    else:
        # 使用随机字符生成ID
        random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
        return f"{prefix}_{timestamp}_{microseconds:03d}_{random_chars}"

def get_template_for_type(test_type):
    """根据测试类型返回相应的模板"""
    templates = {
        "功能测试": {
            "fields": ["id", "title", "precondition", "steps", "expected", "priority", "level", "status", "test_data"],
            "example": {
                "id": "F001",
                "title": "功能测试用例标题",
                "precondition": "测试前置条件",
                "steps": ["步骤1", "步骤2"],
                "expected": "预期结果",
                "priority": "高/中/低",
                "level": "系统级/集成级/单元级",
                "status": "设计中",
                "test_data": {
                    "username": "test_user",
                    "password": "Test@123",
                    "invalid_inputs": ["", "特殊字符@#$"]
                }
            }
        },
        "性能测试": {
            "fields": ["id", "title", "scenario", "load", "duration", "metrics", "threshold", "level", "expected", "test_data"],
            "example": {
                "id": "P001",
                "title": "性能测试用例标题",
                "scenario": "测试场景描述",
                "load": "并发用户数/TPS",
                "duration": "测试持续时间",
                "metrics": ["响应时间", "CPU使用率", "内存使用率"],
                "threshold": "性能指标阈值",
                "level": "压力测试/负载测试/容量测试",
                "expected": "预期结果",
                "test_data": {
                    "user_count": 1000,
                    "ramp_up_time": "30秒",
                    "test_duration": "10分钟"
                }
            }
        },
        "自动化测试": {
            "fields": ["id", "title", "component", "steps", "expected", "automation_level", "level", "data_dependency", "test_data"],
            "example": {
                "id": "A001",
                "title": "自动化测试用例标题",
                "component": "测试组件/模块",
                "steps": ["步骤1", "步骤2"],
                "expected": "预期结果",
                "automation_level": "完全自动化/半自动化",
                "level": "UI级/API级/单元级",
                "data_dependency": "测试数据依赖",
                "test_data": {
                    "test_env": "测试环境",
                    "browser": "Chrome",
                    "test_account": {
                        "username": "auto_test",
                        "password": "Auto@123"
                    }
                }
            }
        }
    }
    
    return templates.get(test_type, templates["功能测试"])

def generate_with_ollama(data):
    """调用 Ollama 生成测试用例"""
    # 获取测试类型对应的模板
    template = get_template_for_type(data['test_type'])
    fields_str = ", ".join(template["fields"])
    
    # 根据优先级策略设置提示
    priority_hints = {
        "1": "请根据测试用例的实际重要性分配优先级，关键功能和核心场景应为高优先级(P0)",
        "2": "请将所有测试用例都设为高优先级(P0)",
        "3": "请将所有测试用例都设为中优先级(P1)",
        "4": "请将所有测试用例都设为低优先级(P2)"
    }
    
    priority_hint = priority_hints.get(data.get('priority_strategy', "1"), priority_hints["1"])
    
    # 测试数据生成提示
    test_data_hint = ""
    if data.get('generate_test_data', True):
        test_data_hint = """
    8. 为每个测试用例生成合理的测试数据，包括：
       - 有效和无效的输入值
       - 边界值和极限条件
       - 特殊字符和格式
       - 与测试场景相关的具体数据
    """
    
    prompt = f"""
    请作为资深测试工程师，根据以下场景生成 {data['number']} 个{data['test_type']}用例：
    - 场景名称: {data['name']}
    - 场景描述: {data['description']}

    请基于上述场景描述，设计全面覆盖该功能的测试用例，包括正向流程、异常流程、边界条件和特殊场景。测试用例应该能够验证该功能的所有关键方面和可能的用户交互路径。

    要求:
    1. 每个用例包含以下字段: {fields_str}
    2. 使用中文描述
    3. 步骤清晰可执行，具体到每个操作步骤
    4. 输出必须是严格的JSON数组格式，不要包含任何其他文本或解释
    5. 请确保JSON格式正确，所有属性名和字符串值都使用双引号
    6. 所有字段必须有有意义的内容，不要留空
    7. {priority_hint}{test_data_hint}
    8. 测试用例应该与场景描述高度相关，确保覆盖描述中提到的所有功能点和业务场景
    9. 用例标题应简洁明了地描述测试目的
    
    JSON格式示例:
    [
      {{
        {json.dumps(template["example"], ensure_ascii=False, indent=8)[1:-1]}
      }}
    ]
    
    请直接返回JSON数组，不要有任何前缀或后缀说明。
    """
    
    try:
        print("\n正在生成测试用例...", end='', flush=True)
        
        # 使用非流式交互
        response = ollama.chat(
            model='llama3.1:8b',
            messages=[{'role': 'user', 'content': prompt}],
            stream=False  # 改为非流式
        )
        
        # 直接获取完整响应
        content = response.get('message', {}).get('content', '')
        print(" 完成！")  # 完成提示
        
        # 保存原始响应以便调试
        with open('raw_response.txt', 'w', encoding='utf-8') as f:
            f.write(content)
        
        # 尝试提取JSON部分
        try:
            # 首先尝试直接解析整个响应
            print("\n尝试解析JSON...")
            return json.loads(content)
        except json.JSONDecodeError as e:
            print(f"\nJSON解析错误: {str(e)}")
            print(f"错误位置: 第{e.lineno}行, 第{e.colno}列")
            print(f"错误的字符: {e.doc[max(0, e.pos-10):e.pos+10]}")
            
            # 如果失败，尝试清理和修复JSON
            print("\n尝试清理和修复JSON...")
            cleaned_json = clean_json_response(content)
            try:
                return json.loads(cleaned_json)
            except json.JSONDecodeError as e2:
                print(f"\n清理后仍然解析失败: {str(e2)}")
                
                # 尝试使用更宽松的JSON解析器
                try:
                    import demjson3
                    print("\n尝试使用demjson3解析...")
                    return demjson3.decode(content)
                except ImportError:
                    print("\ndemjson3未安装，跳过此步骤")
                except Exception as e3:
                    print(f"\ndemjson3解析失败: {str(e3)}")
                
                # 如果仍然失败，尝试提取JSON数组部分
                print("\n尝试提取JSON数组部分...")
                json_pattern = r'\[\s*{.*}\s*\]'
                json_match = re.search(json_pattern, content, re.DOTALL)
                
                if json_match:
                    json_str = json_match.group(0)
                    try:
                        return json.loads(json_str)
                    except json.JSONDecodeError:
                        # 尝试清理提取的JSON
                        cleaned_json_str = clean_json_response(json_str)
                        try:
                            return json.loads(cleaned_json_str)
                        except json.JSONDecodeError:
                            # 如果仍然失败，尝试手动解析
                            print("\n尝试手动解析JSON...")
                            try:
                                # 尝试使用ast.literal_eval作为最后的手段
                                import ast
                                # 将单引号替换为双引号
                                fixed_str = re.sub(r"'", '"', json_str)
                                # 使用ast.literal_eval解析
                                result = ast.literal_eval(fixed_str)
                                return result
                            except Exception as e4:
                                print(f"\n手动解析失败: {str(e4)}")
                                # 如果仍然失败，保存响应以便调试
                                with open('debug_response.txt', 'w', encoding='utf-8') as f:
                                    f.write(content)
                                print("\n错误: 无法解析JSON。已将原始响应保存到debug_response.txt")
                                
                                # 尝试直接使用debug_response.txt中的内容
                                print("\n尝试直接使用已保存的响应...")
                                try:
                                    with open('debug_response.txt', 'r', encoding='utf-8') as f:
                                        debug_content = f.read()
                                    return json.loads(debug_content)
                                except Exception as e5:
                                    print(f"\n使用已保存响应失败: {str(e5)}")
                                    sys.exit(1)
                else:
                    # 保存响应以便调试
                    with open('debug_response.txt', 'w', encoding='utf-8') as f:
                        f.write(content)
                    print("\n错误: 未找到JSON数组。已将原始响应保存到debug_response.txt")
                    sys.exit(1)
    
    except Exception as e:
        print(f"\nOllama 调用失败: {str(e)}")
        sys.exit(1)

def display_test_cases(test_cases):
    """以可读格式显示测试用例"""
    print(f"\n成功生成 {len(test_cases)} 个测试用例:")
    print("-" * 80)
    
    # 按优先级排序
    priority_order = {"高": 0, "中": 1, "低": 2}
    sorted_cases = sorted(test_cases, key=lambda x: priority_order.get(x.get('priority', "低"), 3))
    
    for i, tc in enumerate(sorted_cases, 1):
        # 显示ID、标题和优先级
        print(f"用例 {i}: {tc.get('id', 'N/A')} - {tc.get('title', 'N/A')}")
        
        # 显示优先级（带颜色）
        if 'priority' in tc:
            priority_display = tc.get('priority', 'N/A')
            if priority_display == "高":
                print(f"优先级: \033[1;31mP0\033[0m")  # 红色高亮
            elif priority_display == "中":
                print(f"优先级: \033[1;33mP1\033[0m")  # 黄色高亮
            else:
                print(f"优先级: \033[1;32mP2\033[0m")  # 绿色高亮
        
        # 显示级别
        if 'level' in tc:
            print(f"级别: {tc.get('level', 'N/A')}")
        
        # 显示前置条件（如果有）
        if 'precondition' in tc and tc.get('precondition'):
            print(f"前置条件: {tc.get('precondition')}")
        
        # 显示步骤
        if 'steps' in tc:
            print("步骤:")
            for j, step in enumerate(tc.get('steps', []), 1):
                print(f"  {j}. {step}")
        
        # 显示预期结果
        if 'expected' in tc:
            print(f"预期结果: {tc.get('expected', 'N/A')}")
        
        # 显示测试数据（简化版本）
        if 'test_data' in tc and tc['test_data']:
            print("测试数据: (详细数据见JSON文件)")
        
        print("-" * 80)

def load_test_cases_from_file(filename='debug_response.txt'):
    """从文件中加载测试用例"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        return json.loads(content)
    except Exception as e:
        print(f"\n从文件加载测试用例失败: {str(e)}")
        return []

def generate_test_data(test_case, test_type, scenario_name):
    """根据测试用例类型和场景生成合适的测试数据"""
    if test_type == "功能测试":
        if "登录" in scenario_name or "登陆" in scenario_name or "用户" in scenario_name:
            return {
                "valid_username": "test_user",
                "valid_password": "Test@123",
                "invalid_username": ["", "admin'", "<script>alert(1)</script>", "a"*100],
                "invalid_password": ["", "123", "password", "a"*100],
                "special_chars": ["@#$%^&*", "中文用户名", "user@example.com"]
            }
        elif "搜索" in scenario_name:
            return {
                "keywords": ["手机", "电脑", "衣服", "食品"],
                "special_inputs": ["", "*", "SELECT *", "<script>alert(1)</script>"],
                "long_query": "a" * 100,
                "filters": {
                    "price_range": ["100-500", "1000以上"],
                    "category": ["电子产品", "服装"]
                }
            }
        else:
            return {
                "valid_inputs": ["正常输入1", "正常输入2"],
                "invalid_inputs": ["", "特殊字符@#$", "超长输入"+"a"*50],
                "boundary_values": ["0", "1", "999999"]
            }
    
    elif test_type == "性能测试":
        return {
            "user_count": [10, 50, 100, 500, 1000],
            "ramp_up_time": ["10秒", "30秒", "1分钟"],
            "test_duration": ["5分钟", "10分钟", "30分钟"],
            "think_time": ["1-3秒", "3-5秒"],
            "data_volume": ["小(1KB)", "中(1MB)", "大(10MB)"]
        }
    
    elif test_type == "自动化测试":
        return {
            "test_env": ["开发环境", "测试环境", "预发布环境"],
            "browsers": ["Chrome", "Firefox", "Safari", "Edge"],
            "devices": ["PC", "移动设备", "平板"],
            "screen_sizes": ["1920x1080", "1366x768", "375x812"],
            "test_account": {
                "username": "auto_test",
                "password": "Auto@123"
            }
        }
    
    return {}

def post_process_test_cases(test_cases, data):
    """后处理测试用例，填充缺失字段和调整格式"""
    # 根据测试类型设置测试用例ID前缀
    prefix = ""
    if data['test_type'] == '功能测试':
        prefix = "FUNC"
    elif data['test_type'] == '性能测试':
        prefix = "PERF"
    elif data['test_type'] == '自动化测试':
        prefix = "AUTO"
    
    # 优先级策略
    priority_strategy = data.get('priority_strategy', '1')  # 默认基于重要性
    
    # 处理每个测试用例
    for i, tc in enumerate(test_cases, 1):
        # 替换ID为生成的唯一ID
        tc['id'] = generate_case_id(prefix, i)
        
        # 确保关键字段不为空
        if not tc.get('title') or tc.get('title') == "":
            tc['title'] = f"{data['name']}测试用例 #{i}"
            
        if not tc.get('expected') or tc.get('expected') == "":
            tc['expected'] = f"预期{data['name']}操作成功完成"
        
        # 根据策略设置优先级
        if priority_strategy == "2":  # 全部高优先级
            tc['priority'] = "高"
        elif priority_strategy == "3":  # 全部中优先级
            tc['priority'] = "中"
        elif priority_strategy == "4":  # 全部低优先级
            tc['priority'] = "低"
        # 策略1（基于重要性）保留Ollama生成的优先级，如果没有则设为中
        elif not tc.get('priority') or tc.get('priority') == "":
            tc['priority'] = "中"
            
        # 确保所有测试用例类型都有级别字段
        if not tc.get('level') or tc.get('level') == "":
            if data['test_type'] == '功能测试':
                tc['level'] = random.choice(['系统级', '集成级', '单元级'])
            elif data['test_type'] == '性能测试':
                tc['level'] = random.choice(['压力测试', '负载测试', '容量测试'])
            elif data['test_type'] == '自动化测试':
                tc['level'] = random.choice(['UI级', 'API级', '单元级'])
            
        # 根据测试类型添加额外字段
        if data['test_type'] == '功能测试':
            if not tc.get('status') or tc.get('status') == "":
                tc['status'] = "设计中"
            if not tc.get('precondition') or tc.get('precondition') == "":
                tc['precondition'] = f"用户已进入{data['name']}页面"
            
        if data['test_type'] == '性能测试':
            if not tc.get('threshold') or tc.get('threshold') == "":
                tc['threshold'] = f"响应时间 < {random.randint(100, 500)}ms"
            if not tc.get('duration') or tc.get('duration') == "":
                tc['duration'] = f"{random.randint(5, 30)}分钟"
            if not tc.get('load') or tc.get('load') == "":
                tc['load'] = f"{random.randint(10, 100)}并发用户"
            
        if data['test_type'] == '自动化测试':
            if not tc.get('automation_level') or tc.get('automation_level') == "":
                tc['automation_level'] = random.choice(['完全自动化', '半自动化'])
            if not tc.get('component') or tc.get('component') == "":
                tc['component'] = f"{data['name']}模块"
            if not tc.get('data_dependency') or tc.get('data_dependency') == "":
                tc['data_dependency'] = "测试数据库"
        
        # 如果需要生成测试数据且没有测试数据
        if data.get('generate_test_data', True) and (not tc.get('test_data') or tc.get('test_data') == ""):
            tc['test_data'] = generate_test_data(tc, data['test_type'], data['name'])
        
        # 为数据库准备标签字段
        if not tc.get('tags') or tc.get('tags') == "":
            tc['tags'] = f"{data['name']},{data['test_type']}"
            if tc.get('level'):
                tc['tags'] += f",{tc.get('level')}"
            if data['test_type'] == '功能测试' and tc.get('status'):
                tc['tags'] += f",{tc.get('status')}"
    
    return test_cases

# Add a new function to save test cases to the database
def save_test_cases_to_db(test_cases, scenario_name):
    """Save the test cases to the MySQL database"""
    if not DB_AVAILABLE:
        print("数据库连接不可用，测试用例仅保存到文件")
        return
    
    successful_saves = 0
    failed_saves = 0
    
    print("\n正在将测试用例保存到数据库...")
    
    for tc in test_cases:
        # Map the test case fields to the database schema
        db_test_case = {
            'case_id': tc.get('id', ''),
            'title': tc.get('title', ''),
            'description': tc.get('precondition', '') if tc.get('precondition') else '',
            'content': {
                'steps': tc.get('steps', []),
                'expected_results': tc.get('expected', ''),
                'test_data': tc.get('test_data', {}),
                'level': tc.get('level', ''),
                'precondition': tc.get('precondition', ''),
            }
        }
        
        # Add extra fields based on test type
        if tc.get('threshold'):
            db_test_case['content']['threshold'] = tc.get('threshold')
        if tc.get('duration'):
            db_test_case['content']['duration'] = tc.get('duration')
        if tc.get('load'):
            db_test_case['content']['load'] = tc.get('load')
        if tc.get('automation_level'):
            db_test_case['content']['automation_level'] = tc.get('automation_level')
        if tc.get('component'):
            db_test_case['content']['component'] = tc.get('component')
        if tc.get('data_dependency'):
            db_test_case['content']['data_dependency'] = tc.get('data_dependency')
        
        # Map priority to database format (0=P0 high, 1=P1 medium, 2=P2 low)
        priority_map = {"高": 0, "中": 1, "低": 2}
        db_test_case['priority'] = priority_map.get(tc.get('priority', '中'), 2)
        
        # Map test type to database format
        test_type_map = {
            '功能测试': 1,  # functional
            '性能测试': 4,  # performance
            '自动化测试': 2,  # api (assuming automation tests are API tests)
        }
        db_test_case['test_type'] = test_type_map.get(scenario_name, 1)
        
        # Map status to database format (1=draft, 2=active, 3=archived)
        status_map = {
            '设计中': 1,
            '可执行': 2,
            '已废弃': 3
        }
        db_test_case['status'] = status_map.get(tc.get('status', '设计中'), 1)
        
        # Add tags
        db_test_case['tags'] = tc.get('tags', '')
        
        # Add creator information
        db_test_case['created_by'] = 'Hermes测试用例生成器'
        
        # Save to database
        success, message, case_id = create_test_case(db_test_case)
        if success:
            successful_saves += 1
        else:
            failed_saves += 1
            print(f"保存用例 {tc.get('id', '')} 失败: {message}")
    
    print(f"数据库保存结果: 成功 {successful_saves} 条, 失败 {failed_saves} 条")
    return successful_saves

if __name__ == "__main__":
    input_data = interactive_input()
    print("\n开始生成测试用例...")
    
    try:
        test_cases = generate_with_ollama(input_data)
        # 后处理测试用例
        test_cases = post_process_test_cases(test_cases, input_data)
    except Exception as e:
        print(f"\n生成测试用例失败: {str(e)}")
        print("\n尝试从debug_response.txt加载测试用例...")
        test_cases = load_test_cases_from_file()
        if not test_cases:
            print("\n无法加载测试用例，程序退出")
            sys.exit(1)
    
    # 保存测试用例到文件
    with open('test_cases.json', 'w', encoding='utf-8') as f:
        json.dump(test_cases, f, ensure_ascii=False, indent=2)
    
    # 显示测试用例
    display_test_cases(test_cases)
    
    # 保存测试用例到数据库
    if DB_AVAILABLE:
        save_test_cases_to_db(test_cases, input_data['test_type'])
    
    print("\n生成完成！结果已保存至 test_cases.json")
    if DB_AVAILABLE:
        print("测试用例同时已保存至MySQL数据库")
    pass